//
//  ViewController.m
//  textViewDemo
//
//  Created by Janlor on 12/09/2017.
//  Copyright © 2017 Janlor. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (nonatomic, copy) NSString *text;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.textView.backgroundColor = [UIColor lightGrayColor];
    self.text = @"猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗猫狗";
    
    // 字号
    CGFloat wordSize = [self getWordSize];
    NSLog(@"wordSize = %f", wordSize);
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 20;
    NSMutableDictionary<NSString *, id> *attributesM = [NSMutableDictionary dictionary];
    [attributesM setValue:[UIFont systemFontOfSize:wordSize] forKey:NSFontAttributeName];
    [attributesM setValue:paragraphStyle forKey:NSParagraphStyleAttributeName];
    [attributesM setValue:[UIColor blackColor] forKey:NSForegroundColorAttributeName];
    NSAttributedString *attrText = [[NSAttributedString alloc] initWithString:self.text attributes:attributesM];
    _textView.attributedText = attrText;
}

/// 计算字号
- (CGFloat)getWordSize {
    // 默认最小字号
    CGFloat defaultSize = 15;
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 20;
    
    NSMutableDictionary<NSString *, id> *attributesM = [NSMutableDictionary dictionary];
    [attributesM setValue:paragraphStyle forKey:NSParagraphStyleAttributeName];
    NSAttributedString *attrText = [[NSAttributedString alloc] initWithString:self.text attributes:attributesM];
    self.textView.attributedText = attrText;
    NSLog(@"字体需要高度 = %f， textView高度 = %f", [_textView sizeThatFits:_textView.frame.size].height, _textView.frame.size.height);
    while ([_textView sizeThatFits:_textView.frame.size].height < _textView.frame.size.height) {
        [attributesM setValue:[UIFont systemFontOfSize:defaultSize] forKey:NSFontAttributeName];
        attrText = [[NSAttributedString alloc] initWithString:self.text attributes:attributesM];
        _textView.attributedText = attrText;
        defaultSize++;
    }
    return defaultSize;
}


@end
